//app.js
var Utils = require('/utils/util.js');
var  num = "";

App({
    globalData:{
        host: Utils.Host,
        Rule: Utils.Rule,
        appid: Utils.FootConvenientService.appid,
        path: Utils.FootConvenientService.path,
        envVersion: Utils.FootConvenientService.envVersion,
        orderType: '16',
        bizDoingFlag: "1",
        bizFinishFlag: "2",
        bizAllFlag: "3",
        userInfo: null,
        openId: "",
        channelId: "",
        isAuthSuccess: false,
        cacheData: "CACHE_DATA",  
        cacheOrderPay: 'CACHE_FORM_PAY',
        paySuccess: 'PAY_SUCCESS',
        expressHistory: 'EXPRESS_HISTOrY',
        checkProgress: 'CHECK_PROGRESS', //缓存物流进度
        expressService: 'EXPRESS_SERVICE',
        isHoldAddress: 0

    },

    onLaunch: function () {
	    this.getUserInfo();//jssdk获得用户信息,更新获得用户信息,当服务器挂了第一个请求
    },

    crossToUrl:function (res) {
        if (wx.navigateToMiniProgram) {
        wx.navigateToMiniProgram({
            appId: res.appid,
            path: res.path,
            envVersion: res.envVersion,
            success:function(data) {
                console.log('跳转成功',data)
            },
            fail:function(data){
                console.log('跳转失败',data)
            }
        })
        } else {
            // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },

    toastAuthFailModal:function () {
        wx.showModal({
            title: '微信认证失败',
            content: '请退出“EMS寄快递”，然后再次进入，重新获取微信认证。',
            showCancel: false,
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        });
    },

    //兑换openId
    getUserOpenId: function (callBack) {
      var that = this;
	    if(!this.globalData.openId){
		    wx.login({//调用登录接口
			    success: function (res) {
				    var opt = {//后台兑换openId
					    url: that.globalData.host + "/wx/sd/eo.ajax",
					    data: {
						    'code': res.code
					    },
					    sucFn: function (result) {
                            // that.globalData.openId = result.body.openId;
                            if(result.body.authSuccess) {
                                that.globalData.openId = result.body.openId;
                                that.globalData.isAuthSuccess = result.body.authSuccess;
    						    typeof callBack == "function" && callBack(result.body.openId)
                            } else {
                                that.toastAuthFailModal();
                            }
                          
					    }
				    };
				    that.ajax(opt);
			    }
		    });
	    }else {
			callBack(userOpenId)
      }
    },

    getOpenIdRender(callBack) {
        var that = this;
        var clear = setInterval(() => {
            if (that.globalData.openId) {
                typeof callBack == "function" && callBack(num,that.globalData.openId)
                clearInterval(clear)
            }
        },300)
    },
    //订单数
    getOrderNum: function (callBack) {
      var that = this;
      if(!that.globalData.openId){
	      this.getUserOpenId(function (openId) {
	        // that.globalData.openId = openId;
            that.requestNum(function (num) {
                typeof callBack == "function" && callBack(num,openId)
            })
            that.updateWxUserChannel();
	      })
      }else {
          that.updateWxUserChannel();
	      that.requestNum(function (num) {
		      typeof callBack == "function" && callBack(num)
	      })
      }
    },

    requestNum: function (callBack) {
        var opt2 = {
            url: this.globalData.host+"/wx/sd/list.ajax",
            data: {
                'accountId': this.globalData.openId,
                'bizFlag': this.globalData.bizDoingFlag,
                'orderType': this.globalData.orderType
            },
            sucFn:function (result) {
                if(result.body.orderList.length!=0){
                    num = result.body.orderList.length;
                }
                typeof callBack == "function" && callBack(num)
            }
        };
        this.ajax(opt2);
    },

    getUserInfo: function (cb) {
        var that = this;
        if (this.globalData.userInfo) {
            typeof cb == "function" && cb(this.globalData.userInfo)
        } else {
            wx.login({//调用登录接口
                success: function (res) {
                    wx.getUserInfo({
                        success: function (result) {
                            that.globalData.userInfo = result.userInfo;
                            that.globalData.userInfo['code'] = res.code;
                            var opt = {///授权成功，更新用户信息
                                url: that.globalData.host + "/wx/sd/uwu.ajax",
                                data:that.globalData.userInfo,
                                sucFn: function (data) {
                                }
                            };
                            that.ajax(opt);
                            typeof cb == "function" && cb(that.globalData.userInfo);
                        },
                        fail:function (result) {
                            /*
                            var opt = {//需要查询数据库是否有记录该用户的信息，有就把头像和名称拿出来，没有就用默认的头像
                                url: that.globalData.host + "/wx/ed/gwu.ajax",
                                data: {
                                    'code': res.code
                                },
                                sucFn: function (data) {
                                    that.globalData.userInfo= data.body;
                                }
                            };
                            that.ajax(opt);
                            */
		                        var userObj = {
			                        "avatarUrl": "https://yzres.oss-cn-shenzhen.aliyuncs.com/wx/images/common/mine_default_heard@2x.png",
			                        "nickName": "游客"
		                        };
		                        that.globalData.userInfo = userObj;

                            wx.showModal({
                                title: '微信授权失败',
                                content: '请在小程序列表完全删除邮证快递，然后再次扫描二维码进入，允许小程序获取您的用户信息。',
                                showCancel:false,
                                success: function(res) {
                                    if (res.confirm) {
                                        console.log('用户点击确定');
                                    } else if (res.cancel) {
                                        console.log('用户点击取消');
                                    }
                                }
                            })

                        }
                    })
                }
            })
        }
    },
    makePhoneCall:function (phone) {
        wx.makePhoneCall({
            phoneNumber: phone //仅为示例，并非真实的电话号码
        });
    },
    toYMDHMSDate:function (number) {
       return Utils.toYMDHMSDate(number);
    },
    toYMDDate:function (number) {
       return Utils.toYMDDate(number);
    },
    toast:function (mes,icon) {
        Utils.toast(mes, icon);
    },
    loadToast:function (time) {
        var duration = (time == null || time == "" || typeof(time) == "undefined") ? 60000 : time;
        wx.showToast({
            title: '加载中',
            icon: 'loading',
            duration:duration,
            mask:true
        })
    },
    hideToast:function() {
        wx.hideToast()
    },
    ajax:function (opt) {
        var that = this;
        opt['pageObj'] = this.getCurrentPage();
        opt.data['WX_OPENID'] = this.globalData.openId||''; //this.globalData.openId;
        opt.data['WX_CHANNEL'] = this.globalData.channelId||'';
        opt['accountIdBlankFn'] = function () {
            Utils.errorToast(that.getCurrentPage(), "网络错误");
            that.globalData.openId = "";
            that.globalData.isAuthSuccess = false;
        };
        Utils.ajax(opt);
    },
    errorToast:function(mes) {
        Utils.errorToast(this.getCurrentPage(), mes);
    },
    hidePopErrorMes:function() {
        Utils.hidePopErrorMes(this.getCurrentPage());
    },
    check:function(jsonArray) {
        return Utils.check(jsonArray,this.getCurrentPage());
    },
    initAddress:function (callBack){
        Utils.initAddress(this.getCurrentPage(),callBack);
    },
    bindAddressChange:function (e){
        Utils.bindAddressChange(e,this.getCurrentPage());
    },
    initHkHouse:function (){
        Utils.initHkHouse(this.getCurrentPage());
    },
    initTwHouse:function (){
        Utils.initTwHouse(this.getCurrentPage());
    },
    bindHkHouseChange:function (e){
        Utils.bindHkHouseChange(e,this.getCurrentPage());
    },
    bindTWHouseChange:function (e) {
        Utils.bindTWHouseChange(e,this.getCurrentPage());
    },
    /**封装微信的方法,统一入口，方便后续做统一的处理**/
    navigateTo:function (data) {
        wx.navigateTo({
          url: data.url,
          success: function(res){
              if (!(data.success==null || data.success=="" || typeof(data.success)=="undefined")){
                  data.success(res);
              }
          },
          fail: function() {
              if (!(data.fail==null || data.fail=="" || typeof(data.fail)=="undefined")){
                  data.fail(res);
              }
          },
          complete: function() {
              if (!(data.complete==null || data.complete=="" || typeof(data.complete)=="undefined")){
                  data.complete(res);
              }
          }
        })
    },
    redirectTo:function (data) {
        wx.redirectTo({
        url: data.url,
        success: function(res){
            if (!(data.success==null || data.success=="" || typeof(data.success)=="undefined")){
                data.success(res);
            }
        },
        fail: function() {
            if (!(data.fail==null || data.fail=="" || typeof(data.fail)=="undefined")){
                data.fail(res);
            }
        },
        complete: function() {
            if (!(data.complete==null || data.complete=="" || typeof(data.complete)=="undefined")){
                 data.complete(res);
            }
        }
        })
    },
    getStorageSync:function (key) {
        return wx.getStorageSync(key);
    },
    setStorageSync:function (key,value) {
         wx.setStorageSync(key,value);
    },
    removeStorageSync:function (key) {
        try {
            wx.removeStorageSync(key)
        } catch (e) {
            // Do something when catch error
        }
    },
    removeStorage:function (key) {
        wx.removeStorage({key: key, success: function(res) {} });
    },
    identityCodeValid:function(code) {
    var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
    var tip = "";
    var pass= true;

    if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
      tip = "身份证号格式错误";
      pass = false;
    }

    else if(!city[code.substr(0,2)]){
      tip = "地址编码错误";
      pass = false;
    }
    else{
      //18位身份证需要验证最后一位校验位
      if(code.length == 18){
        code = code.split('');
        //∑(ai×Wi)(mod 11)
        //加权因子
        var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
        //校验位
        var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
        var sum = 0;
        var ai = 0;
        var wi = 0;
        for (var i = 0; i < 17; i++)
        {
          ai = code[i];
          wi = factor[i];
          sum += ai * wi;
        }
        var last = parity[sum % 11];
        if(parity[sum % 11] != code[17]){
          tip = "校验位错误";
          pass =false;
        }
      }
    }
    return pass;
    },
    isAndroid:function () {
        var res = wx.getSystemInfoSync()
        if(res.model.indexOf('iPhone')>-1){
          return false;
        }else {
          return true;
        }
    },

	requestPayment:function (opt) {
	    Utils.requestPayment(opt);
    },
    updateWxUserChannel:function () {
        var that = this;
        var opt = {
            url: that.globalData.host + "/wx/sd/uwu.ajax",
            data:{
                openId:that.globalData.openId,
                wxChannel:that.globalData.channelId
            },
            sucFn: function (data) {

            }
        };
        that.ajax(opt);
    }
});